import React, { useRef, useEffect, useState } from 'react';
import Draggable from 'react-draggable';
import Crop, { PixelCrop } from 'react-image-crop'; 
import 'react-image-crop/dist/ReactCrop.css';

interface DraggableCropImageProps {
  src: string;
  alt: string;
}

const DraggableCropImage: React.FC<DraggableCropImageProps> = ({ src, alt }) => {
  const imgRef = useRef<HTMLImageElement>(null);
  const [crop, setCrop] = useState<PixelCrop>({
    unit: 'px',
    width: 100,
    height: 100,
    x: 0,
    y: 0,
  });
  const [completedCrop, setCompletedCrop] = useState<PixelCrop | null>(null);

  useEffect(() => {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          if (imgRef.current && !imgRef.current.src) {
            imgRef.current.src = src;
          }
        }
      });
    });

    if (imgRef.current) {
      observer.observe(imgRef.current);
    }

    return () => {
      if (imgRef.current) {
        observer.unobserve(imgRef.current);
      }
    };
  }, [src]);

  const onCropComplete = (crop: PixelCrop) => {
    setCompletedCrop(crop);
  };

  return (
    <div style={{ position: 'relative', marginBottom: '20px' }}>
      <Draggable>
        <div style={{ border: '1px solid #ccc', display: 'inline-block', position: 'relative' }}>
          <Crop
            crop={crop}
            onChange={(newCrop) => setCrop(newCrop)}
            onComplete={onCropComplete}
            style={{ width: '300px', height: 'auto' }}
          >
            <img ref={imgRef} alt={alt} style={{ display: 'block', width: '100%' }} />
          </Crop>
        </div>
      </Draggable>
    </div>
  );
};

export default DraggableCropImage;